#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

using namespace std;

class Solution {
public:
    bool wordPattern(string pattern, string s) {
      const vector<string>& vt = SplitStr(s);
      if (vt.size() != pattern.length()) {
        return false;
      }

      unordered_map<char, string> strMap;
      unordered_map<string, char> chMap;
      for (int idx = 0; idx < pattern.length(); idx++) {
        auto itCh = chMap.find(vt[idx]);
        auto itstr = strMap.find(pattern[idx]);

        if (itCh == chMap.end() && itstr == strMap.end()) {
          chMap.insert({ vt[idx], pattern[idx] });
          strMap.insert({ pattern[idx], vt[idx] });
        } else if (itCh != chMap.end()) {
          if (itCh->second != pattern[idx]) {
            return false;
          }
        } else if (itstr != strMap.end()) {
          if (itstr->second != vt[idx]) {
            return false;
          }
        }
      }
      
      return true;
    }

    vector<string> SplitStr(const string& s)
    {
      vector<string> vt{};
      string strNew = s + " ";
      while (strNew.length() != 0) {
        auto pos = strNew.find(' ');
        if (pos != string::npos) {
          string tmp = strNew.substr(0, pos);
          vt.push_back(tmp);
          strNew = strNew.substr(pos + 1);
        }
      }
      return vt;
    }
};

int main()
{
  Solution s;
  string pattern = "abba";
  string str = "dog dog dog dog";
  cout << boolalpha << s.wordPattern(pattern, str) << endl;
  return 0;
}